package com.irdstudio.efp.nls.service.impl.psd.timedTask;

import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.constant.StdZbHandleEnums;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.util.DateUtility;
import com.irdstudio.basic.framework.core.util.SpringContextUtils;
import com.irdstudio.basic.sequence.service.facade.PatternedLimitableSeqService;
import com.irdstudio.efp.console.service.facade.PtProductUserService;
import com.irdstudio.efp.console.service.vo.PtProductUserVO;
import com.irdstudio.efp.ctr.service.facade.CtrLoanContService;
import com.irdstudio.efp.ctr.service.vo.CtrLoanContVO;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.edoc.service.bo.CfcaSignInfoVO;
import com.irdstudio.efp.edoc.service.facade.CfcaSignInfoService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.service.bo.req.frontsystem.MobileBankInfoReqBean;
import com.irdstudio.efp.esb.service.bo.req.hlw.ReqAlarmJudgementBean;
import com.irdstudio.efp.esb.service.bo.req.ydxxzf.GainOrderReqBean;
import com.irdstudio.efp.esb.service.bo.req.ydxxzf.GeneratorOrderReqBean;
import com.irdstudio.efp.esb.service.bo.resp.frontsystem.MobileBankInfoRespBean;
import com.irdstudio.efp.esb.service.bo.resp.hlw.RespAlarmJudgementBean;
import com.irdstudio.efp.esb.service.bo.resp.ydxxzf.GainOrderRespBean;
import com.irdstudio.efp.esb.service.bo.resp.ydxxzf.GeneratorOrderRespBean;
import com.irdstudio.efp.esb.service.facade.EsbInvokeWrapper;
import com.irdstudio.efp.esb.service.facade.frontsystem.MobileBankInfoService;
import com.irdstudio.efp.esb.service.facade.hlw.AlarmJudgementService;
import com.irdstudio.efp.esb.service.facade.ydxxzf.GainOrderService;
import com.irdstudio.efp.esb.service.facade.ydxxzf.GeneratorOrderService;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.service.facade.NlsPublicService;
import com.irdstudio.efp.nls.service.facade.NlsQueueSoltComnService;
import com.irdstudio.efp.nls.service.facade.psd.PsdSqsSignatureService;
import com.irdstudio.efp.nls.service.facade.psd.PsdTaskReqInfoService;
import com.irdstudio.efp.nls.service.facade.psd.TaskHandleService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.psd.PsdTaskReqInfoVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.*;

/**
 * 需求编号:2019D08--
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/12/16
 * 功能描述:
 * 修改日期:2019/12/16
 * 修改描述:
 */
@Service("taskHandleService")
public class TaskHandleServiceImpl implements TaskHandleService {
    private static Logger logger = LoggerFactory.getLogger(TaskHandleServiceImpl.class);

    @Override
    public void updateTaskInfo() {
        PsdTaskReqInfoVO psdTaskReqInfo = null;
        try {
            List<PsdTaskReqInfoVO> psdTaskReqInfoVOS = psdTaskReqInfoService.selectRecordByHandleStatus(200);
            if (!psdTaskReqInfoVOS.isEmpty()) {
                for (PsdTaskReqInfoVO psdTaskReqInfoVO : psdTaskReqInfoVOS) {
                    psdTaskReqInfo = psdTaskReqInfoVO;
                    GainOrderReqBean gainOrderReqBean = new GainOrderReqBean();
                    gainOrderReqBean.setWrkOrdrId(psdTaskReqInfoVO.getOrderId());
                    gainOrderReqBean.setGlobaNo(psdTaskReqInfoVO.getGlobaNo());
                    try {
                        GainOrderRespBean gainOrderRespBean = gainOrderService.applygainOrder(gainOrderReqBean);
                        // 调用定时任务时更新
                        List<GainOrderRespBean.WrkOrdrDealInfArry> wrkOrdrDealInfArry = gainOrderRespBean.getWrkOrdrDealInfArry();
                        if (Objects.nonNull(wrkOrdrDealInfArry) && !wrkOrdrDealInfArry.isEmpty()) {
                            GainOrderRespBean.WrkOrdrDealInfArry wrkOrdrDealInf = wrkOrdrDealInfArry.get(0);
                            if (Objects.nonNull(wrkOrdrDealInf)) {
                                psdTaskReqInfoVO.setHandleStatus(wrkOrdrDealInf.getStCd());
                                psdTaskReqInfoVO.setHandleResult(wrkOrdrDealInf.getDealRslt());
                                psdTaskReqInfoVO.setDeptName(wrkOrdrDealInf.getDeptNm());
                                psdTaskReqInfoVO.setProductName(wrkOrdrDealInf.getPdNm());
                                psdTaskReqInfoVO.setProductSystem(wrkOrdrDealInf.getPdBlngSysIndr());
                                psdTaskReqInfoVO.setDealUserId(wrkOrdrDealInf.getActlHndlrId());
                                psdTaskReqInfoVO.setDealName(wrkOrdrDealInf.getActlHndlrNm());
                                psdTaskReqInfoVO.setLoginName(wrkOrdrDealInf.getLgnNm());
                                psdTaskReqInfoVO.setCreateStatus(300);
                                psdTaskReqInfoVO.setLastUpdateTime(new Date());
                                psdTaskReqInfoService.updateByPrimaryKey(psdTaskReqInfoVO);
                            }
                        }
                    } catch (ESBException e) {
                        logger.error("工单ID：【" + psdTaskReqInfoVO.getOrderId() + "】普税贷任务处理阶段查询任务信息失败!!!" + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("工单ID：【" + psdTaskReqInfo.getOrderId() + "普税贷任务处理阶段查询未更新任务信息失败!!!" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void createTaskInfo() {
        PsdTaskReqInfoVO psdTaskReqInfo = null;
        List<PsdTaskReqInfoVO> psdTaskReqInfoVOS = null;
        try {
            psdTaskReqInfoVOS = psdTaskReqInfoService.selectRecordByHandleStatus(201);
            if (psdTaskReqInfoVOS == null || psdTaskReqInfoVOS.isEmpty()) {
                logger.info("查询创建工单待处理的记录数据为空，本次定时器结束");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询创建工单待处理的记录数据异常", e);
            return;
        }
        for (PsdTaskReqInfoVO psdTaskReqInfoVO : psdTaskReqInfoVOS) {
            try {
                psdTaskReqInfo = psdTaskReqInfoVO;
                NlsCreditInfoVO vo = new NlsCreditInfoVO();
                vo.setLmtApplySeq(psdTaskReqInfoVO.getLmtApplySeq());
                NlsCreditInfoVO query = nlsCreditInfoService.queryByPk(vo);

                GeneratorOrderReqBean generatorOrderReqBean = new GeneratorOrderReqBean();
                generatorOrderReqBean.setWrkOrdrId(psdTaskReqInfoVO.getOrderId());
                generatorOrderReqBean.setStCd(psdTaskReqInfoVO.getHandleStatus());
                generatorOrderReqBean.setCustMgrNo(psdTaskReqInfoVO.getManagerId());
                generatorOrderReqBean.setPdNo(psdTaskReqInfoVO.getProductId());
                if ("1".equals(psdTaskReqInfoVO.getTaskTyp())) {
                    generatorOrderReqBean.setBrchId(query.getOperateAgency());
                } else {
                    generatorOrderReqBean.setBrchId(query.getNlsOperOrgid());
                }
                generatorOrderReqBean.setCustNm(psdTaskReqInfoVO.getCusName());
                generatorOrderReqBean.setGnd(psdTaskReqInfoVO.getGender());
                generatorOrderReqBean.setTelNo(psdTaskReqInfoVO.getTelPhone());
                generatorOrderReqBean.setIdentNo(psdTaskReqInfoVO.getIdNum());
                generatorOrderReqBean.setIdentTp(psdTaskReqInfoVO.getIdType());
                generatorOrderReqBean.setEntpNm(psdTaskReqInfoVO.getCorpName());
                generatorOrderReqBean.setUnfdSoclCrdtCd(psdTaskReqInfoVO.getSocialCode());
                generatorOrderReqBean.setEntpRgstAddr(psdTaskReqInfoVO.getAddress());
                generatorOrderReqBean.setUsrFlg(psdTaskReqInfoVO.getUserType());
                generatorOrderReqBean.setLoanLmt(Optional.ofNullable(psdTaskReqInfoVO.getQuota()).orElse(new BigDecimal("0")).doubleValue());
                generatorOrderReqBean.setLoanTrm(query.getApplyTerm());
                generatorOrderReqBean.setCltlInf(psdTaskReqInfoVO.getMortgage());
                generatorOrderReqBean.setRemark(psdTaskReqInfoVO.getRemark());
                generatorOrderReqBean.setLmtApplySeq(psdTaskReqInfoVO.getGlobaNo());
                GeneratorOrderRespBean generatorOrderRespBean = generatorOrderService.applyGeneratorOrder(generatorOrderReqBean);

                if (!EsbBizEnums.RetCodeEnum.SUCCESS.VALUE.equals(generatorOrderRespBean.getRetCd())) {
                    if (!BaseConstant.YES_Y.equals(psdTaskReqInfoVO.getWarnFlag())) {
                        String alrmInf = "网贷普税贷产品工单创建，根据机构号：" + generatorOrderReqBean.getBrchId() + generatorOrderRespBean.getRetMsg();
                        // 调用告警判断服务
                        ReqAlarmJudgementBean imageFileReqBean = new ReqAlarmJudgementBean();
                        imageFileReqBean.setMonObjNm("网贷普税贷产品工单创建");
                        imageFileReqBean.setMonObjSpfTpVal("网贷批量");
                        try {
                            imageFileReqBean.setMonObjLctr(InetAddress.getLocalHost().getHostAddress());// 应用地址
                        } catch (Exception e) {
                            imageFileReqBean.setMonObjLctr("efp_nls");
                        }
                        imageFileReqBean.setAlrmInf(alrmInf);
                        imageFileReqBean.setAlrmTmstmp(DateUtility.getCurrAppDateTimeString());
                        imageFileReqBean.setMonAlrmLvl("2");
                        RespAlarmJudgementBean imageFileRespBean = alarmJudgementService.alarmJudgement(imageFileReqBean);
                        logger.info("调用告警返回码：【" + imageFileRespBean.getRetCd() + "】，返回信息：【" + imageFileRespBean.getRetMsg() + "】");
                        if ("0000".equals(imageFileRespBean.getRetCd())) {
                            psdTaskReqInfoVO.setWarnFlag(BaseConstant.YES_Y);
                        }
                    }
                } else {
                    // 更新补充信息
                    updateOrgandUsr(psdTaskReqInfoVO, generatorOrderRespBean);
                }

                psdTaskReqInfoVO.setCreateStatus(EsbBizEnums.RetCodeEnum.SUCCESS.VALUE.equals(generatorOrderRespBean.getRetCd()) ? 200 : 201);
                psdTaskReqInfoVO.setHandleResult(generatorOrderRespBean.getRetMsg());
                psdTaskReqInfoVO.setCreateMsg(generatorOrderRespBean.getRetMsg());
                psdTaskReqInfoVO.setLastUpdateTime(new Date());
                psdTaskReqInfoService.updateByPrimaryKey(psdTaskReqInfoVO);

            } catch (Exception e) {
                logger.error("工单ID：【" + psdTaskReqInfo.getOrderId() + "普税贷任务处理阶段工单创建失败!!!" + e.getMessage());
                e.printStackTrace();
            }
        }


    }

    private void updateOrgandUsr(PsdTaskReqInfoVO inVo, GeneratorOrderRespBean generatorOrderRespBean) throws BizException {
        NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
        String applySeq = inVo.getLmtApplySeq();
        nlsCreditInfoVO.setLmtApplySeq(applySeq);
        NlsCreditInfoVO nlsCreditInfoVO1 = nlsCreditInfoService.queryByPk(nlsCreditInfoVO);
        String userId = generatorOrderRespBean.getActlHndlrId();
        PtProductUserVO ptProduceUser = ptProductUserService.getPtProduceByLoginName(userId);
        Optional.ofNullable(ptProduceUser).orElseThrow(() -> new BizException("任务处理阶段 查询不到客户经理信息"));
        String orgId = ptProduceUser.getDeptId();
        inVo.setDeptId(orgId);
        inVo.setManagerId(orgId);
        if ("1".equals(inVo.getTaskTyp())) {
            nlsCreditInfoVO.setOperateAgencyUser(userId);
            nlsCreditInfoVO.setOperateAgency(orgId);
            int k = nlsCreditInfoService.updateByPk(nlsCreditInfoVO);
            if (k != 1) {
                logger.info("更新异常，根据授信流水号" + nlsCreditInfoVO.getLmtApplySeq() + "更新记录" + k + "条");
                throw new BizException("更新异常");
            }
            sendMsg("1", ptProduceUser, nlsCreditInfoVO1);
        } else {
            nlsCreditInfoVO.setNlsOperOrgid(orgId);
            nlsCreditInfoVO.setNlsOperUserid(userId);
            nlsCreditInfoVO.setOperateAgencyUser(userId);
            nlsCreditInfoVO.setOperateAgency(orgId);
            int k = nlsCreditInfoService.updateByPk(nlsCreditInfoVO);
            if (k != 1) {
                logger.info("更新异常，根据授信流水号" + nlsCreditInfoVO.getLmtApplySeq() + "更新记录" + k + "条");
                throw new BizException("更新异常");
            }
            // 2. 更新额度表的经理信息
            LmtPrdContVO lmtPrdContVO = new LmtPrdContVO();
            lmtPrdContVO.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
            lmtPrdContVO = lmtPrdContService.queryByPk(lmtPrdContVO);
            LmtPrdContVO lmtPrdCont = new LmtPrdContVO();
            lmtPrdCont.setLmtContNo(lmtPrdContVO.getLmtContNo());
            lmtPrdCont.setMainBrId(orgId);
            lmtPrdCont.setChargeoffBrId(orgId);
            lmtPrdCont.setCusManager(userId);
            int m = lmtPrdContService.updateByPk(lmtPrdCont);
            if (m != 1) {
                logger.info("更新异常，根据授信协议编号" + lmtPrdCont + "更新记录" + m + "条");
                throw new BizException("更新异常");
            }
            // 3. 更新客户信息表的信息
            CusIndivVO indivVO = new CusIndivVO();
            indivVO.setCusId(nlsCreditInfoVO1.getCusId());
            indivVO.setCusManager(userId);
            indivVO.setPerformanceOwner(userId);
            indivVO.setPerformanceOrg(orgId);
            int i = cusIndivService.updateByPk(indivVO);
            if (i != 1) {
                logger.info("更新异常，根据客户号" + nlsCreditInfoVO1.getCusId() + "更新记录" + i + "条");
                throw new BizException("更新异常");
            }
            // 4. 更新签章信息表的信息
            CfcaSignInfoVO cfcaSignInfoVO = new CfcaSignInfoVO();
            cfcaSignInfoVO.setApplySeq(applySeq);
            // 网贷经办机构
            cfcaSignInfoVO.setNlsOperOrgid(orgId);
            // 网贷经办人
            cfcaSignInfoVO.setNlsOperUserid(userId);
            // 账务机构
            cfcaSignInfoVO.setFinaBrId(orgId);
            cfcaSignInfoService.updateByPk(cfcaSignInfoVO);
            psdSqsSignatureService.updateOperInfo(applySeq, userId, orgId);
            // 5. 更新合同信息表的信息
            CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
            ctrLoanContVO.setContNo(applySeq);
            ctrLoanContVO.setPerformanceOwner(userId);
            ctrLoanContVO.setPerformanceOrg(orgId);
            ctrLoanContVO.setCusManager(userId);
            ctrLoanContVO.setInputBrId(orgId);
            ctrLoanContVO.setMainBrId(orgId);
            ctrLoanContVO.setFinaBrId(orgId);
            ctrLoanContVO.setLegalOrgCode(orgId);
            int n = ctrLoanContService.updateByPk(ctrLoanContVO);
            if (n != 1) {
                logger.info("更新异常，根据合同编号" + ctrLoanContVO.getContNo() + "更新记录" + n + "条");
                throw new BizException("更新异常");
            }
            sendMsg("2", ptProduceUser, nlsCreditInfoVO1);
        }

    }

    /**
     * 下发短信
     *
     * @param stage           下发场景
     * @param ptProduceUser   客户经理信息
     * @param nlsCreditInfoVO 授信申请信息
     */
    private void sendMsg(String stage, PtProductUserVO ptProduceUser, NlsCreditInfoVO nlsCreditInfoVO) {
        CusIndivVO cusPkParam = new CusIndivVO();
        cusPkParam.setCusId(nlsCreditInfoVO.getCusId());
        CusIndivVO cusIndivVO = cusIndivService.queryByPk(cusPkParam);
        if (Objects.isNull(cusIndivVO)) {
            logger.error("根据客户号{}获取客户信息失败", cusPkParam.getCusId());
        }
        LmtPrdContVO lmtPkParam = new LmtPrdContVO();
        lmtPkParam.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        LmtPrdContVO lmtPrdContVO = lmtPrdContService.queryByPk(lmtPkParam);
        if (Objects.isNull(lmtPrdContVO)) {
            logger.error("根据授信流水号{}获取额度信息失败", lmtPkParam.getLmtApplySeq());
        }
        String phone = cusIndivVO.getPhone();
        if (StringUtils.isBlank(phone)) {
            //下发短信
            logger.info("获取客户手机号为空，无法进行短信下发");
            return;
        }
        if ("1".equals(stage)) {
            //无一类户卡号 也就是新用户
            nlsPublicService.sendMessageWithCusManagerInfo("1", lmtPrdContVO, ptProduceUser, phone);
            return;
        }
        if ("2".equals(stage)) {
            //有一类户卡号，需要判断是否签约手机银
            try {
                boolean b = invokeMobileBankQuery(nlsCreditInfoVO);
                if (b) {
                    nlsPublicService.sendMessageWithCusManagerInfo("3", lmtPrdContVO, ptProduceUser, phone);
                } else {
                    nlsPublicService.sendMessageWithCusManagerInfo("2", lmtPrdContVO, ptProduceUser, phone);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("查询客户是否签约手机银行异常", e);
            }
        }

    }

    private boolean invokeMobileBankQuery(NlsCreditInfoVO selectCreditInfo) throws Exception {
        MobileBankInfoRespBean resp = null;
        MobileBankInfoReqBean res = new MobileBankInfoReqBean();
        res.setGlobaNo(selectCreditInfo.getGlobalSerno());
        //操作类型身份证
        res.setIdentTp(selectCreditInfo.getCertType());
        // 证件号码
        res.setOprtTp("1");
        //操作渠道代码：网络信贷系统
        res.setOprtChanFlg("07");
        res.setIdentTp(selectCreditInfo.getCertType());
        res.setIdentNo(selectCreditInfo.getCertCode());
        resp = (MobileBankInfoRespBean) new EsbInvokeWrapper(mobileBankInfoService, res, nlsQueueSoltComnService).invoke3Threes();
        if (Objects.isNull(resp)) {
            return false;
        }
        return StringUtils.isNotEmpty(resp.getMblBnkCustNo());
    }


    @Autowired
    @Qualifier("psdTaskReqInfoService")
    private PsdTaskReqInfoService psdTaskReqInfoService;

    @Autowired
    @Qualifier("gainOrderService")
    private GainOrderService gainOrderService;

    @Autowired
    @Qualifier("generatorOrderService")
    private GeneratorOrderService generatorOrderService;

    @Autowired
    @Qualifier("ptProductUserService")
    private PtProductUserService ptProductUserService;

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("cfcaSignInfoService")
    private CfcaSignInfoService cfcaSignInfoService;

    @Autowired
    @Qualifier("psdSqsSignatureService")
    private PsdSqsSignatureService psdSqsSignatureService;

    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    @Autowired
    @Qualifier("alarmJudgementService")
    private AlarmJudgementService alarmJudgementService;// 告警服务


    @Autowired
    @Qualifier("nlsPublicService")
    private NlsPublicService nlsPublicService;

    @Autowired
    private MobileBankInfoService mobileBankInfoService;

    @Autowired
    private NlsQueueSoltComnService nlsQueueSoltComnService;

}
